// -----------------------------------------------------------------------
// <copyright file="EditWithDataReaderAndDirectSql.aspx.cs" company="Imar.Spaanjaars.Com">
//   Copyright 2008 - 2009 - Imar.Spaanjaars.Com. All rights reserved.
// </copyright>
// -----------------------------------------------------------------------

using System;
using System.Configuration;
using System.Data.SqlClient;

public partial class Alternatives_EditWithDataReaderAndDirectSql : System.Web.UI.Page
{
  protected void Page_Load(object sender, EventArgs e)
  {
    if (!Page.IsPostBack)
    {
			// Get the first person in the database so we can edit it. Normally, you would use something like the QueryString to get the right record.
			string sql = @"SELECT TOP 1 FirstName, LastName, MiddleName FROM ContactPerson ORDER BY Id ASC";
      using (SqlConnection myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["NLayer"].ConnectionString))
      {
        using (SqlCommand myCommand = new SqlCommand(sql, myConnection))
        {
          myConnection.Open();
          using (SqlDataReader myReader = myCommand.ExecuteReader())
          {
            if (myReader.Read())
            {
              txtFirstName.Text = myReader.GetString(0);
              txtLastName.Text = myReader.GetString(1);
              if (!myReader.IsDBNull(2))
              {
                txtMiddleName.Text = myReader.GetString(2);
              }
            }
            myReader.Close();
          }
          myConnection.Close();
        }
      }
    }
  }

  protected void btnSave_Click(object sender, EventArgs e)
  {
		// Get the first person in the database and update it. Normally, you would use something like the QueryString to get the right record.
		string sqlBase = @"UPDATE ContactPerson SET FirstName='{0}', LastName='{1}', MiddleName ='{2}' WHERE Id = (SELECT TOP 1 Id FROM ContactPerson ORDER BY Id ASC)";
    using (SqlConnection myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["NLayer"].ConnectionString))
    {
      string sql = string.Format(sqlBase, txtFirstName.Text, txtLastName.Text, txtMiddleName.Text);
      SqlCommand myCommand = new SqlCommand(sql, myConnection);
      myConnection.Open();
      myCommand.ExecuteNonQuery();
      myConnection.Close();
    }
  }
}
